package com.spzx.order.service.impl;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.cart.api.RemoteCartService;
import com.spzx.cart.api.domain.CartInfo;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.DateUtils;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.common.rabbit.service.RabbitService;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.order.domain.*;
import com.spzx.order.mapper.OrderItemMapper;
import com.spzx.order.mapper.OrderLogMapper;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.domain.ProductSku;
import com.spzx.product.api.domain.SkuPrice;
import com.spzx.product.api.domain.vo.SkuLockVo;
import com.spzx.user.api.RemoteUserAddressService;
import com.spzx.user.api.domain.UserAddress;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import com.spzx.order.mapper.OrderInfoMapper;
import com.spzx.order.service.IOrderInfoService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

/**
 * 订单Service业务层处理
 *
 * @author atguigu
 * @date 2024-09-28
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService
{
    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private RemoteCartService remoteCartService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RemoteProductService remoteProductService;

    @Autowired
    private RemoteUserAddressService remoteUserAddressService;

    @Autowired
    private OrderLogMapper orderLogMapper;

    @Autowired
    private RabbitService rabbitService;

    /**
     * 查询订单列表
     *
     * @param orderInfo 订单
     * @return 订单
     */
    @Override
    public List<OrderInfo> selectOrderInfoList(OrderInfo orderInfo)
    {
        return orderInfoMapper.selectOrderInfoList(orderInfo);
    }

    /**
     * 查询订单
     *
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public OrderInfo selectOrderInfoById(Long id)
    {
        OrderInfo orderInfo = orderInfoMapper.selectById(id);
        List<OrderItem> orderItemList = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, id));
        orderInfo.setOrderItemList(orderItemList);
        return orderInfo;
    }

    @Override
    public TradeVo orderTradeData() {
        // 获取当前登录用户的Id
        Long userId = SecurityContextHolder.getUserId();
        // 调用cart-api获取购物车中选中的商品
        R<List<CartInfo>> cartCheckedListResult = remoteCartService.getCartCheckedList(userId, SecurityConstants.INNER);
        // 判断响应结果
        if (cartCheckedListResult.getCode() == R.FAIL) {
            throw new ServiceException(cartCheckedListResult.getMsg());
        }
        // 获取选中的商品列表
        List<CartInfo> cartCheckedList = cartCheckedListResult.getData();
        if (CollectionUtils.isEmpty(cartCheckedList)){
            throw new ServiceException("购物车中无选中的商品");
        }
        // 将集合数据类型从CartInfo转化为OrderItem
        List<OrderItem> orderItemList = cartCheckedList.stream().map(cartInfo -> {
            OrderItem orderItem = new OrderItem();
            BeanUtils.copyProperties(cartInfo, orderItem);
            orderItem.setSkuNum(cartInfo.getSkuNum());
            return orderItem;
        }).toList();
        // 计算订单总金额
        BigDecimal totalAmount = new BigDecimal(0);
        // 遍历计算
        for (OrderItem orderItem : orderItemList) {
            // 订单总金额 = 所有的相加 (商品单价*商品数量)
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        // 生成订单号
        String tradeNo = this.generateTradeNo(userId);
        // 封装返回数据
        TradeVo tradeVo = new TradeVo();
        tradeVo.setTradeNo(tradeNo);
        tradeVo.setOrderItemList(orderItemList);
        tradeVo.setTotalAmount(totalAmount);

        return tradeVo;
    }

    /**
     * 用户提交订单
     * @param orderForm
     * @return Long
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long submitOrder(OrderForm orderForm) {
        // 获取当前登录的用户Id
        Long userId = SecurityContextHolder.getUserId();
        // 1.验证用户是否通过浏览器回退进行重复提交订单
        // 1.1获取redis中的订单流水号 跟用户提交的订单号进行比较
        // Boolean isValid = this.checkTradeNo(userId.toString(), orderForm.getTradeNo());
        // if (!isValid) {
        //     throw new ServiceException("订单已提交，请勿重复提交");
        // }
        // 1.2 验证通过 将redis中的流水号删除
        //this.deleteTradeNo(userId.toString());

        // 1.3 采用lua脚本保证删除订单流水号的原子性 KEYS[1]:流水号Key  ARGV[1]：用户流水号
        String userTradeKey = "user:tradeNo:" + userId;
        // 如果根据userTradeKey在redis中查询的订单流水号 跟用户提交的订单号相等 则删除流水号 否则返回0
        String scriptText = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                "then\n" +
                "    return redis.call(\"del\",KEYS[1])\n" +
                "else\n" +
                "    return 0\n" +
                "end";
        // 执行脚本
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
        redisScript.setScriptText(scriptText);
        redisScript.setResultType(Long.class);
        // 判断根据userId查询到的订单号是否与上一步结算界面生成的redis中的交易码一致
        Long flag = (Long) redisTemplate.execute(redisScript, Arrays.asList(userTradeKey), orderForm.getTradeNo());
        if (flag == 0) {
            throw new ServiceException("请勿重复提交订单，请尝试重试");
        }
        // 2.判断购物项列表是否为空8
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        if (CollectionUtils.isEmpty(orderItemList)) {
            throw new ServiceException("请求不合法");
        }
        // 3.订单校验
        // 3.1 校验价格
        // 获取购物项的id集合
        List<Long> skuIdList = orderItemList.stream().map(OrderItem::getSkuId).toList();
        // 调用product-api 查询sku价格
        R<List<SkuPrice>> skuPriceListResult = remoteProductService.getSkuPriceList(skuIdList, SecurityConstants.INNER);
        if (R.FAIL == skuPriceListResult.getCode()) {
            throw new ServiceException(skuPriceListResult.getMsg());
        }
        List<SkuPrice> skuPriceList = skuPriceListResult.getData();
        // 封装skuId与实时价格到一个Map<Long, BigDecimal>
        Map<Long, BigDecimal> skuIdToSalePriceMap = skuPriceList.stream().collect(Collectors.toMap(SkuPrice::getSkuId, SkuPrice::getSalePrice));
        String priceCheckResult = "";

        // for (OrderItem orderItem : orderItemList) {
        //     if (!orderItem.getSkuPrice().equals(skuIdToSalePriceMap.get(orderItem.getSkuId()))) {
        //          priceCheckResult += orderItem.getSkuName() + "价格变化了; ";
        //     }
        // }
        // if(StringUtils.isNotEmpty(priceCheckResult)) {
        //     //更新购物车价格
        //     remoteCartService.updateCartPrice(userId, SecurityConstants.INNER);
        //     // todo
        //     throw new ServiceException(priceCheckResult);
        // }

        // 老师的代码
        for (OrderItem orderItem : orderItemList) {
            int i = orderItem.getSkuPrice().compareTo(skuIdToSalePriceMap.get(orderItem.getSkuId()));
            if (i != 0) {
                // 如果实时价格校验失败，需要更新缓存中的价格数据
                remoteCartService.updateCartPrice(userId, SecurityConstants.INNER);
                throw new RuntimeException("实时价格校验失败");
            }
        }

        //3.2.校验库存并锁定库存
        //TODO 已补充

        // 遍历订单项列表，封装为库存锁定对象SkuLockVo
        List<SkuLockVo> skuLockVoList = orderItemList.stream().map(orderItem -> {
            SkuLockVo skuLockVo = new SkuLockVo();
            skuLockVo.setSkuId(orderItem.getSkuId());
            skuLockVo.setSkuNum(orderItem.getSkuNum());
            return skuLockVo;
        }).toList();
        // 远程调用 检查并锁定库存
        String checkAndLockResult = remoteProductService.checkAndLock(orderForm.getTradeNo(), skuLockVoList, SecurityConstants.INNER).getData();
        // 如果有库存锁定失败的提示信息，抛出异常
        if(StringUtils.isNotEmpty(checkAndLockResult)) {
            throw new ServiceException(checkAndLockResult);
        }

        Long orderId = null;
        try {
            //4 下单
            orderId = this.saveOrder(orderForm);
        } catch (Exception e) {
            e.printStackTrace();
            //4.1 下单失败，解锁库存
            rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT, MqConst.QUEUE_UNLOCK, orderForm.getTradeNo());
            //抛出异常
            throw new ServiceException("下单失败");
        }
        //5 删除购物车选项
        remoteCartService.deleteCartCheckedList(userId, SecurityConstants.INNER);
        // todo
        //6 发送延迟消息，取消订单
        rabbitService.sendDelayMessage(MqConst.EXCHANGE_CANCEL_ORDER, MqConst.ROUTING_CANCEL_ORDER, String.valueOf(orderId), MqConst.CANCEL_ORDER_DELAY_TIME);
        return orderId;
    }

    /**
     * 立即购买
     * @param skuId
     * @return TradeVo
     */
    @Override
    public TradeVo buy(Long skuId) {
        // 根据skuID调用remoteProductService获取sku的信息
        R<ProductSku> productSkuResult = remoteProductService.getProductSku(skuId, SecurityConstants.INNER);
        if (R.FAIL == productSkuResult.getCode()) {
            throw new ServiceException(productSkuResult.getMsg());
        }
        ProductSku productSku = productSkuResult.getData();
        // 封装订单项列表orderItemList
        List<OrderItem> orderItemList = new ArrayList<>();
        OrderItem orderItem = new OrderItem();
        orderItem.setSkuId(skuId);
        orderItem.setSkuName(productSku.getSkuName());
        orderItem.setSkuNum(1);
        orderItem.setSkuPrice(productSku.getSalePrice());
        orderItem.setThumbImg(productSku.getThumbImg());
        orderItemList.add(orderItem);

        //订单总金额
        BigDecimal totalAmount = productSku.getSalePrice();

        //渲染订单确认页面-生成用户流水号
        String tradeNo = this.generateTradeNo(SecurityUtils.getUserId());
        // 封装结算项tradeVo
        TradeVo tradeVo = new TradeVo();
        tradeVo.setTotalAmount(totalAmount);
        tradeVo.setOrderItemList(orderItemList);
        tradeVo.setTradeNo(tradeNo);
        return tradeVo;
    }

    @Override
    public List<OrderInfo> selectUserOrderInfoList(Integer orderStatus) {
        // 获取当前登录的用户的userId
        Long userId = SecurityContextHolder.getUserId();
        // 查询用户的订单信息列表orderInfoList
        List<OrderInfo> orderInfoList =  orderInfoMapper.selectUserOrderInfoList(userId, orderStatus);
        // 不写sql
        // List<OrderInfo> orderInfoList = this.list(new LambdaQueryWrapper<>(OrderInfo.class)
        //         .eq(userId !=null,OrderInfo::getUserId, userId)
        //         .eq(orderStatus !=null,OrderInfo::getOrderStatus, orderStatus));
        if (!CollectionUtils.isEmpty(orderInfoList)){ // 少写一个！
            // 获得订单id集合
            List<Long> orderIdList = orderInfoList.stream().map(OrderInfo::getId).toList();
            // 根据订单id集合查询订单项列表
            List<OrderItem> orderItemList = orderItemMapper.selectList(new LambdaQueryWrapper<>(OrderItem.class)
                    .in(OrderItem::getOrderId, orderIdList));
            // 将orderItemList转化为一个map<Long, List<OrderItem>> 按照orderId分组
            Map<Long, List<OrderItem>> orderIdToOrderItemListMap = orderItemList.stream().collect(Collectors.groupingBy(OrderItem::getOrderId));
            // 将orderItemList按照orderId封装进orderInfo中
            orderInfoList.forEach(orderInfo -> orderInfo.setOrderItemList(orderIdToOrderItemListMap.get(orderInfo.getId())));
        }
        return orderInfoList;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void processCloseOrder(long orderId) {
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        if(null != orderInfo && orderInfo.getOrderStatus() == 0) {
            orderInfo.setOrderStatus(-1);
            orderInfo.setCancelTime(new Date());
            orderInfo.setCancelReason("未支付自动取消");
            orderInfoMapper.updateById(orderInfo);

            //记录日志
            OrderLog orderLog = new OrderLog();
            orderLog.setOrderId(orderInfo.getId());
            orderLog.setProcessStatus(-1L);
            orderLog.setNote("系统取消订单");
            orderLogMapper.insert(orderLog);

            //发送MQ消息通知商品系统解锁库存
            rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT, MqConst.QUEUE_UNLOCK, orderInfo.getOrderNo());
        }
    }

    @Override
    public void cancelOrder(Long orderId) {
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        if(null != orderInfo && orderInfo.getOrderStatus() == 0) {
            orderInfo.setOrderStatus(-1);
            orderInfo.setCancelTime(new Date());
            orderInfo.setCancelReason("用户取消订单");
            orderInfoMapper.updateById(orderInfo);
            //记录日志
            OrderLog orderLog = new OrderLog();
            orderLog.setOrderId(orderInfo.getId());
            orderLog.setProcessStatus(-1L);
            orderLog.setNote("用户取消订单");
            orderLogMapper.insert(orderLog);
            //发送MQ消息通知商品系统解锁库存
            rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT, MqConst.QUEUE_UNLOCK, orderInfo.getOrderNo());
        }
    }

    @Override
    public void cancelOrder(Long orderId) {
        // 根据orderId查询订单信息
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        // 判断订单状态是否为未支付
        if(null != orderInfo && orderInfo.getOrderStatus() == 0) {
            // 更新订单状态为已取消
            orderInfo.setOrderStatus(-1);
            orderInfo.setCancelTime(new Date());
            orderInfo.setCancelReason("用户取消订单");
            orderInfoMapper.updateById(orderInfo);
            //记录日志
            OrderLog orderLog = new OrderLog();
            orderLog.setOrderId(orderInfo.getId());
            orderLog.setProcessStatus(-1L);
            orderLog.setNote("用户取消订单");
            orderLogMapper.insert(orderLog);
            //发送MQ消息通知商品系统解锁库存
            rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT, MqConst.QUEUE_UNLOCK, orderInfo.getOrderNo());
        }
    }

    @Override
    public void processPaySuccess(String orderNo) {
        // 获取订单信息
        OrderInfo orderInfo = orderInfoMapper.selectOne(new LambdaQueryWrapper<>(OrderInfo.class)
                .eq(OrderInfo::getOrderNo, orderNo).select(OrderInfo::getId, OrderInfo::getOrderStatus));
        // 如果未支付
        if (orderInfo.getOrderStatus() == 0){
            // 设置支付状态
            orderInfo.setOrderStatus(1);
            orderInfo.setPaymentTime(new Date());
            orderInfoMapper.updateById(orderInfo);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public Long saveOrder(OrderForm orderForm) {
        // 获取当前登录用户的id
        Long userId = SecurityContextHolder.getUserId();
        // 获取当前登录用户的用户名
        String userName = SecurityContextHolder.getUserName();
        // 封装订单信息orderInfo
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderNo(orderForm.getTradeNo());
        orderInfo.setUserId(userId);
        orderInfo.setNickName(userName);
        orderInfo.setRemark(orderForm.getRemark());
        // 根据UserAddressId获取收货地址信息
        UserAddress userAddress = remoteUserAddressService.getUserAddress(orderForm.getUserAddressId(), SecurityConstants.INNER).getData();
        // 封装订单信息orderInfo中的收货人信息
        orderInfo.setReceiverName(userAddress.getName());
        orderInfo.setReceiverPhone(userAddress.getPhone());
        orderInfo.setReceiverTagName(userAddress.getTagName());
        orderInfo.setReceiverProvince(userAddress.getProvinceCode());
        orderInfo.setReceiverCity(userAddress.getCityCode());
        orderInfo.setReceiverDistrict(userAddress.getDistrictCode());
        orderInfo.setReceiverAddress(userAddress.getFullAddress());
        // 获取购物项列表OrderItemList
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        // 遍历购物项列表计算总金额
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        // 封装订单信息orderInfo中的金额数据
        orderInfo.setTotalAmount(totalAmount);
        orderInfo.setCouponAmount(new BigDecimal(0));
        orderInfo.setOriginalTotalAmount(totalAmount);
        orderInfo.setFeightFee(orderForm.getFeightFee());
        //OrderInfo类的orderStatus属性的类型改为Integer
        orderInfo.setOrderStatus(0);
        // 保存订单信息
        orderInfoMapper.insert(orderInfo);

        //保存每个订单项详细信息
        for (OrderItem orderItem : orderItemList) {
            orderItem.setOrderId(orderInfo.getId());
            orderItemMapper.insert(orderItem);
        }

        //记保存记录日志
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderInfo.getId());
        orderLog.setProcessStatus(0L);
        orderLog.setNote("提交订单");
        orderLogMapper.insert(orderLog);

        // 返回订单id
        return orderInfo.getId();
    }
    /**
     * 验证页面提交流水号是否有效
     *
     * @param userId
     * @param tradeNo
     * @return
     */
    private Boolean checkTradeNo(String userId, String tradeNo) {
        String userTradeKey = "user:tradeNo:" + userId;
        String redisTradeNo = (String) redisTemplate.opsForValue().get(userTradeKey); // stringRedisTemplate会出现多一对双引号的序列化问题
        return tradeNo.equals(redisTradeNo);
    }
    /**
     * 删除流水号
     *
     * @param userId
     */
    private void deleteTradeNo(String userId) {
        String userTradeKey = "user:tradeNo:" + userId;
        redisTemplate.delete(userTradeKey);
    }


    /**
     * 渲染订单确认页面-生成用户流水号
     *
     * @param userId
     * @return
     */
    private String generateTradeNo(Long userId) {
        //1.构建流水号Key
        String userTradeKey = "user:tradeNo:" + userId;
        //2.构建流水号value
        String tradeNo = UUID.randomUUID().toString().replaceAll("-", "");
        //3.将流水号存入Redis 暂存5分钟
        redisTemplate.opsForValue().set(userTradeKey, tradeNo, 5, TimeUnit.MINUTES);
        return tradeNo;
    }

}
